<template>
    <div style="width: 100%;">
        <custom-tabbar title="个人资料" />
        <!-- <image src="/static/english/english_top_bg.png" class="topBg" /> -->
        <div class="avar">
            <image :src="userInfo.cover ? userInfo.cover : '/static/my/default_avar.png'" class="cover" @click="changeAvar" mode="aspectFill"></image>
            <div class="nickname">
                {{ userInfo.nickname }}
                <image src="/static/my/edit.png" class="icon_edit" @click="showName = true"></image>
            </div>
        </div>
        <div class="info">
            <div class="birthday" @click="show = true">
                <span>生日</span>
                <div class="arrow" :style="{color: userInfo.birthday === null ? '#B3B3B3' : '#333333'}">
                    {{ userInfo.birthday === null ? '请选择您的生日' : `${userInfo.birthday[0]+'-'+userInfo.birthday[1]+'-'+ userInfo.birthday[2] }` }}
                    <image src="/static/my/icon_arrow.png" style="width: 48rpx; height: 48rpx;"></image>
                </div>
            </div>
            <div class="sex" @click="showSex = true">
                <span>性别</span>
                <div class="arrow" :style="{color: userInfo.sex === null ? '#B3B3B3' : '#333333'}">
                    {{ userInfo.sex !== null ? sextoString(userInfo.sex) : '请选择您的性别'}}
                    <image src="/static/my/icon_arrow.png" style="width: 48rpx; height: 48rpx;"></image>
                </div>
            </div>
        </div>
        <div class="phone">
            <div class="phone_title">账号绑定</div>
            <div class="phone_content" v-if="Number(userInfo.phone)">
                <div class="phone_content_left">
                    <image src="./phone.svg" style="width: 48rpx; height: 48rpx;"></image>
                    <span style="margin-left: 12rpx;">手机</span>
                </div>
                <div class="phone_content_right" :style="{color: userInfo.birthday ? '#B3B3B3' : '#333333'}">
                    {{Number(userInfo.phone) ? userInfo.phone : '未绑定' }}
                    <image src="/static/my/icon_arrow.png" :style="{width: '48rpx', height: '48rpx', visibility: Number(userInfo.phone) ? 'hidden' : 'unset'}"></image>
                </div>
            </div>
            <button class="phone_content" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-else>
                <div class="phone_content_left">
                    <image src="./phone.svg" style="width: 48rpx; height: 48rpx;"></image>
                    <span style="margin-left: 12rpx;">手机</span>
                </div>
                <div class="phone_content_right" :style="{color: userInfo.birthday ? '#B3B3B3' : '#333333'}">
                    {{Number(userInfo.phone) ? userInfo.phone : '未绑定' }}
                    <image src="/static/my/icon_arrow.png" :style="{width: '48rpx', height: '48rpx', visibility: Number(userInfo.phone) ? 'hidden' : 'unset'}"></image>
                </div>
            </button>
        </div>
        <div class="button" @click="handleSave" style="visibility: hidden;">
            保存
        </div>
        <birthdayModal 
            :show="show" 
            :year='userInfo.birthday !== null ? userInfo.birthday[0] : userInfo.birthday' 
            :month = 'userInfo.birthday !== null ? userInfo.birthday[1] : userInfo.birthday' 
            :day = 'userInfo.birthday !== null ? userInfo.birthday[2] : userInfo.birthday' 
            @close ='()=>{show = false}'
            @onConfirm = 'onConfirm'
        />
        <sexModal :show = 'showSex' :sex="userInfo.sex" @close ='()=>{showSex = false}' @select="changeSex" />
        <changeNameModal :show = 'showName' @close ='()=>{showName = false}' @onConfirm = 'changeName' />
    </div>
</template>

<script setup>
    import { ref, onMounted, reactive } from 'vue'
    import customTabbar from '@/components/customTabbar/index.vue';
    import birthdayModal from '@/components/birthdayModal/index.vue';
    import sexModal from '@/components/sexModal/index.vue';	
    import changeNameModal from '@/components/changeNameModal/index.vue';
    import { onLoad } from '@dcloudio/uni-app';
    import { getUserInfoApi, bindPhoneApi, updateUserInfoApi, updateAvarApi, getOssApi } from '@/apis/index';
    import { dateFormat, Toast } from '@/utils/tools';
    import { MD5 } from 'crypto-js';
    import { uploadFileOs } from '@/apis/upload';
    import { AesDecrypt } from '@/utils/aes';
    const userInfo = reactive({
        nickname: '张小米',
        cover: '',
        birthday: [2000, 11, 26],
        sex: '男',
        phone: '1381****6672'
    })
    const show = ref(false);
    const showSex = ref(false);
    const showName = ref(false);
    onLoad(()=>{
        getUserInfo(false);
    })
    const getUserInfo =  async (update) =>{
        const { obj } = await getUserInfoApi();
        if(update){
            userInfo.phone = obj.username;
            return;
        }
        userInfo.nickname = obj.realname; 
        userInfo.cover = obj.avar;
        userInfo.phone = obj.username;
        userInfo.sex = obj.sex;
        let birthday = obj.birthday;
        if(obj.birthday){
            const time = dateFormat(obj.birthday, 'YYYY-MM-DD');
            birthday = time.split('-');
        }
        userInfo.birthday = birthday;
    }   
    const getPhoneNumber= (e) =>{
        console.log('getPhoneNumber', e);
        bindPhone(e)
    }
    const bindPhone = async (e) => {
        uni.login({
            provider: 'weixin',
            success: async function ({code}) {
                const data = {
                    code,
                    phoneCode: e.detail.code,
                    source:2,
                };
                const res = await bindPhoneApi(data);
                getUserInfo(true);
            }
        });
    }
    const onConfirm = async (e) => {
        console.log('onConfirm', e);
        userInfo.birthday = e;
		const data = {
		    birthday: `${e[0]}-${e[1] }-${e[2]}` ,
		    sex: null,
		    name: userInfo.nickname,
		}
		if(userInfo.sex !== '' && userInfo.sex !== null){
			data.sex = sextoString(userInfo.sex)
		}
		const res = await updateUserInfoApi(data)
    }
    const sextoString = (data) =>{
        switch (data) {
            case 'male':
                return '男';
            case 'female':
                return '女';
            case '男':
                return '男';
            case '女':
                return '女';
            default:
                return null;
        }
    }
    const handleSave = async() => {
        const data = {
            birthday: `${userInfo.birthday[0]}-${userInfo.birthday[1] }-${userInfo.birthday[2]}`,
            sex: sextoString(userInfo.sex),
            name: userInfo.nickname,
        }
        const res = await updateUserInfoApi(data)
        getUserInfo();
    }
    const changeAvar = () =>{
        uni.chooseMedia({
            count: 1,
            mediaType: ['image','video'],
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            camera: 'back',
            success({tempFiles}) {
                const tempFilePath = tempFiles[0].tempFilePath;
                const index = tempFilePath.lastIndexOf('.');
                const suffix = tempFilePath.substr(index + 1);
                const fileName = getAvarName(suffix);
                getOSS(fileName,  tempFilePath);
            }
        })
    }
    const getAvarName= (suffix) => {
        const day  = dateFormat(new Date().getTime(), 'YYYYMMDD');
        const md5 = MD5(userInfo.nickname).toString().substring(8, 16);
        const code = getRanDomCode(8);
        return `avar/yc/${day}/${md5}/HS_${code}.${suffix}`
    }
    const getRanDomCode= (length) => {
        const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        let randomCode = "";
        for (let i = 0; i < length; i++) {
            const randomIndex = Math.floor(Math.random() * characters.length);
            randomCode += characters.charAt(randomIndex);
        }
        return randomCode;
    }
    const  getOSS = async(fileName, tempFilePath) => {
        const { obj } = await getOssApi({flag: 1});
        const ossDt = JSON.parse(AesDecrypt(obj));
        const parmas = Object.assign({}, ossDt, {
            dir: fileName,
            filePath: tempFilePath
        });
        const res = await uploadFileOs(parmas);
        uploadAvar(fileName);
	}
    const uploadAvar = async (fileName)=>{
        const { obj } = await updateAvarApi({userAvar: '/' + fileName});
        userInfo.cover = obj;
        Toast({title: '修改成功', duration: 2000})
    }
	const changeName = async (name) => {
		userInfo.nickname = name
		const data = {
		    birthday: null,
		    sex: null,
		    name
		}
		if(userInfo.sex !== '' && userInfo.sex !== null){
			data.sex = sextoString(userInfo.sex)
		}
		if(userInfo.birthday !== '' && userInfo.birthday !== null){
			// data.birthday = `${userInfo.birthday[0]}-${ Number(userInfo.birthday[1]) < 10 ? '0'+ Number(userInfo.birthday[1]) : userInfo.birthday[1] }-${ Number(userInfo.birthday[2]) < 10 ? '0'+ Number(userInfo.birthday[2]) : userInfo.birthday[2]}`
			data.birthday = `${userInfo.birthday[0]}-${userInfo.birthday[1] }-${userInfo.birthday[2]}`
		}
		const res = await updateUserInfoApi(data)
	}
	const changeSex = async(type)=>{
		userInfo.sex = type;
		const data = {
		    birthday: null,
		    sex: sextoString(type),
		    name: userInfo.nickname
		}
		if(userInfo.birthday !== '' && userInfo.birthday !== null){
			data.birthday = `${userInfo.birthday[0]}-${userInfo.birthday[1] }-${userInfo.birthday[2]}`
		}
		const res = await updateUserInfoApi(data)
		Toast({title:res.msg, duration:2000})
	}
</script>

<style lang="scss">
.topBg{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 445rpx;
    z-index: -1;
}
.avar {
    width: 100%;
    height: 300rpx;
    // background-color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .cover{
        width: 118rpx;
        height: 118rpx;
        border-radius: 59rpx;
    }
    .nickname{
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-top: 20rpx;
        .icon_edit{
            width: 32rpx;
            height: 32rpx;
            margin-left: 10rpx;
        }
    }
}
.info{
    margin-top: 18rpx;
    background: #fff;
    .birthday, .sex{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        padding-left: 32rpx;
        padding-top: 25rpx;
        padding-bottom: 25rpx;
        padding-right: 20rpx;
        font-size: 28rpx;
        .arrow{
            display: flex;
            justify-content: center;
            align-content: center;
        }
    }
    .birthday{
        border-bottom: 1px solid rgba(0,0,0,0.1);
    }
}
.phone{
    .phone_title{
        margin: 20rpx 32rpx;
        font-size: 28rpx;
        color: #B3B3B3;
    }
    .phone_content{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding-left: 32rpx;
        padding-top: 25rpx;
        padding-bottom: 25rpx;
        padding-right: 20rpx;
        background-color: #fff;
        .phone_content_left, .phone_content_right{
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 28rpx;
        }
    }
}
.button{
    position: fixed;
    width: calc(100% - 64rpx);
    border-radius: 40rpx;
    bottom: 88rpx;
    margin:  0 32rpx;
    padding: 20rpx 0;
    background: linear-gradient( 315deg, #68edc5 0%, #51b7ff 100%);
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>